"""
量化分析模块（核心）
从stock_analyzer.py迁移，保持API不变，但支持配置
"""

from config import current_config as config


class QuantitativeAnalyzer:
    """量化分析引擎（保持向后兼容，增强可配置性）"""
    
    def __init__(self, realtime_data, historical_data):
        self.realtime = realtime_data
        self.hist = historical_data
        self.signals = []
        self.score = 0
        
    def analyze_trend(self):
        """趋势分析"""
        signals = []
        score = 0
        
        if self.hist is None or len(self.hist) < 60:
            return signals, score
        
        latest = self.hist.iloc[-1]
        current_price = latest['收盘']
        
        # 均线多头排列
        ma_scores = 0
        if 'MA5' in latest and 'MA10' in latest and 'MA20' in latest and 'MA60' in latest:
            if latest['MA5'] > latest['MA10'] > latest['MA20'] > latest['MA60']:
                signals.append("✅ 均线呈多头排列，趋势向上")
                ma_scores += 30
            elif latest['MA5'] < latest['MA10'] < latest['MA20'] < latest['MA60']:
                signals.append("❌ 均线呈空头排列，趋势向下")
                ma_scores -= 20
            
            if current_price > latest['MA20']:
                signals.append("✅ 股价站上20日均线")
                ma_scores += 10
            
            if current_price > latest['MA60']:
                signals.append("✅ 股价站上60日均线")
                ma_scores += 10
        
        score += ma_scores
        return signals, score
    
    def analyze_macd(self):
        """MACD分析"""
        signals = []
        score = 0
        
        if 'MACD' not in self.hist.columns or len(self.hist) < 2:
            return signals, score
        
        latest = self.hist.iloc[-1]
        prev = self.hist.iloc[-2]
        
        if prev['DIF'] <= prev['DEA'] and latest['DIF'] > latest['DEA']:
            signals.append("🚀 MACD金叉，买入信号")
            score += 25
        elif prev['DIF'] >= prev['DEA'] and latest['DIF'] < latest['DEA']:
            signals.append("⚠️ MACD死叉，卖出信号")
            score -= 25
        
        if latest['MACD'] > 0 and latest['MACD'] > prev['MACD']:
            signals.append("✅ MACD红柱增长，动能增强")
            score += 15
        elif latest['MACD'] < 0 and latest['MACD'] < prev['MACD']:
            signals.append("❌ MACD绿柱增长，下跌动能增强")
            score -= 15
        
        return signals, score
    
    def analyze_kdj(self):
        """KDJ分析"""
        signals = []
        score = 0
        
        if 'K' not in self.hist.columns or len(self.hist) < 2:
            return signals, score
        
        latest = self.hist.iloc[-1]
        prev = self.hist.iloc[-2]
        
        if latest['K'] < 20 and latest['D'] < 20:
            signals.append("💎 KDJ超卖区域，可能反弹")
            score += 20
        elif latest['K'] > 80 and latest['D'] > 80:
            signals.append("⚠️ KDJ超买区域，注意回调")
            score -= 20
        
        if prev['K'] <= prev['D'] and latest['K'] > latest['D'] and latest['K'] < 50:
            signals.append("🚀 KDJ低位金叉，强烈买入信号")
            score += 25
        elif prev['K'] >= prev['D'] and latest['K'] < latest['D'] and latest['K'] > 50:
            signals.append("⚠️ KDJ高位死叉，卖出信号")
            score -= 25
        
        return signals, score
    
    def analyze_rsi(self):
        """RSI分析"""
        signals = []
        score = 0
        
        if 'RSI6' not in self.hist.columns:
            return signals, score
        
        latest = self.hist.iloc[-1]
        
        if latest['RSI6'] < 30:
            signals.append("💎 RSI超卖，可能反弹")
            score += 15
        elif latest['RSI6'] > 70:
            signals.append("⚠️ RSI超买，注意风险")
            score -= 15
        
        if 'RSI12' in latest and 'RSI24' in latest:
            if 30 < latest['RSI6'] < 50:
                signals.append("✅ RSI处于合理区间")
                score += 10
        
        return signals, score
    
    def analyze_boll(self):
        """布林带分析"""
        signals = []
        score = 0
        
        if 'BOLL_UPPER' not in self.hist.columns:
            return signals, score
        
        latest = self.hist.iloc[-1]
        current_price = latest['收盘']
        
        if current_price <= latest['BOLL_LOWER']:
            signals.append("💎 股价触及布林带下轨，可能反弹")
            score += 20
        elif current_price >= latest['BOLL_UPPER']:
            signals.append("⚠️ 股价触及布林带上轨，可能回调")
            score -= 15
        elif current_price > latest['BOLL_MID']:
            signals.append("✅ 股价在布林带中上轨")
            score += 10
        
        return signals, score
    
    def analyze_volume(self):
        """成交量分析"""
        signals = []
        score = 0
        
        if self.realtime is None:
            return signals, score
        
        volume_ratio = self.realtime['量比']
        turnover = self.realtime['换手率']
        
        if volume_ratio > 2:
            signals.append("🔥 量比大于2，成交活跃")
            score += 15
        elif volume_ratio > 1.5:
            signals.append("✅ 量比适中，关注度提升")
            score += 10
        elif volume_ratio < 0.5:
            signals.append("⚠️ 量比过低，交投清淡")
            score -= 10
        
        if 3 < turnover < 7:
            signals.append("✅ 换手率适中，活跃度良好")
            score += 10
        elif turnover > 10:
            signals.append("🔥 换手率高，资金活跃")
            score += 15
        elif turnover < 1:
            signals.append("⚠️ 换手率低，流动性不足")
            score -= 5
        
        return signals, score
    
    def analyze_price_position(self):
        """价格位置分析"""
        signals = []
        score = 0
        
        if self.realtime is None:
            return signals, score
        
        current = self.realtime['最新价']
        high = self.realtime['最高价']
        low = self.realtime['最低价']
        
        if high != low:
            position = (current - low) / (high - low) * 100
            
            if position > 90:
                signals.append("🚀 股价接近全天最高点")
                score += 15
            elif position < 10:
                signals.append("💎 股价接近全天最低点")
                score += 10
        
        change_pct = self.realtime['涨跌幅']
        if change_pct > 5:
            signals.append("🔥 今日涨幅超5%，强势上涨")
            score += 20
        elif change_pct > 2:
            signals.append("✅ 今日上涨超2%，表现良好")
            score += 15
        elif change_pct < -5:
            signals.append("⚠️ 今日跌幅超5%，注意风险")
            score -= 20
        elif change_pct < -2:
            signals.append("⚠️ 今日下跌超2%，走势偏弱")
            score -= 10
        
        return signals, score
    
    def comprehensive_analysis(self):
        """综合分析"""
        all_signals = []
        total_score = 0
        
        trend_signals, trend_score = self.analyze_trend()
        macd_signals, macd_score = self.analyze_macd()
        kdj_signals, kdj_score = self.analyze_kdj()
        rsi_signals, rsi_score = self.analyze_rsi()
        boll_signals, boll_score = self.analyze_boll()
        volume_signals, volume_score = self.analyze_volume()
        price_signals, price_score = self.analyze_price_position()
        
        all_signals.extend(trend_signals)
        all_signals.extend(macd_signals)
        all_signals.extend(kdj_signals)
        all_signals.extend(rsi_signals)
        all_signals.extend(boll_signals)
        all_signals.extend(volume_signals)
        all_signals.extend(price_signals)
        
        total_score = (trend_score + macd_score + kdj_score + 
                      rsi_score + boll_score + volume_score + price_score)
        
        normalized_score = max(0, min(100, 50 + total_score / 2))
        
        return all_signals, normalized_score
    
    def generate_recommendation(self, score):
        """生成投资建议（支持自定义阈值）"""
        thresholds = config.SCORE_THRESHOLDS
        
        if score >= thresholds['strong_buy']:
            return "🚀 强烈买入", "多项技术指标显示强势上涨趋势，建议积极关注买入机会", "success"
        elif score >= thresholds['buy']:
            return "✅ 买入", "技术面整体向好，可以考虑适量买入", "success"
        elif score >= thresholds['hold']:
            return "👀 观望", "技术指标表现一般，建议继续观察", "warning"
        elif score >= thresholds['sell']:
            return "⚠️ 减仓", "技术面偏弱，建议谨慎或减仓", "warning"
        else:
            return "❌ 卖出", "多项指标显示下跌风险，建议及时止损", "error"

